package com.online.olsrootserver.handler;

import com.online.olsrootserver.builder.TextBuilder;
import com.online.olsrootserver.entity.Customer;
import com.online.olsrootserver.service.CompanyService;
import com.online.olsrootserver.service.CustomerService;
import com.online.olsrootserver.service.FindAentServer;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by littleheng on 2018/4/25
 * 关注事件
 */
@Component
public class SubscribeHandler extends AbstractHandler {

    @Autowired
    private FindAentServer sessionManageCluster;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private CompanyService companyService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMpXmlMessage, Map<String, Object> map, WxMpService wxMpService, WxSessionManager wxSessionManager) throws WxErrorException {

        //  获取微信用户openId
        String customerOpenId = wxMpXmlMessage.getFromUser();
        String companyOpenId = wxMpXmlMessage.getToUser();

        //  获取微信用户基本信息
        WxMpUser userWxInfo = wxMpService.getUserService()
                .userInfo(customerOpenId, "zh_CN");
        String companyId = this.companyService.getIdByWxNumber(companyOpenId);
        String address = userWxInfo.getCountry() + userWxInfo.getProvince() + userWxInfo.getCity();

        Map<String, Object> redisParams = new HashMap<>();
        redisParams.put("open_id", customerOpenId);

        //  查询微信用户在redis中是否存在
        Map redisResult = this.sessionManageCluster.getWeChatUser(redisParams);
        System.out.println(redisResult);
        //  不存在就新增到redis
        if (Integer.parseInt(redisResult.get("result").toString()) == 0) {
            System.out.println("不存在就新增到redis");
            Map<String, Object> saveRedisParamsMap = new HashMap<>();
            saveRedisParamsMap.put("open_id", customerOpenId);
            saveRedisParamsMap.put("name", userWxInfo.getNickname());
            saveRedisParamsMap.put("address", address);
            saveRedisParamsMap.put("e_id", Integer.parseInt(companyId));
            saveRedisParamsMap.put("sex", userWxInfo.getSexDesc());

            Map result = this.sessionManageCluster.saveWeChatUser(saveRedisParamsMap);

            System.out.println("新增用户信息到redis成功");
            if (Integer.parseInt(result.get("result").toString()) == 0) {
                this.logger.info("新增用户信息到redis成功");
            } else {
                this.logger.info("参数异常");
            }
        }

        // 查询微信用户在数据库中是否存在
        int customerNum = this.customerService.checkCustomer(customerOpenId);
        //  新增顾客到数据库
        if (customerNum == 0) {
            Customer customer = new Customer();
            Timestamp d = new Timestamp(System.currentTimeMillis());
            String sex = userWxInfo.getSex() == 2 ? "0" : "1";

            customer.setOpenId(customerOpenId);
            customer.setUserName(userWxInfo.getNickname());
            customer.setAddress(address);
            customer.setSex(sex);
            customer.setCompanyId(companyId);
            customer.setCreateTime(d);
            customer.setSubscribeStatus("1");

            int result = this.customerService.addCustomer(customer);
            if (result > 0) {
                this.logger.info("新增顾客到数据库成功");
            }
            //  更新顾客关注状态
        } else if (customerNum == 1) {
            int result = this.customerService.modifySubscribeStatus(customerOpenId, "1");
            if (result > 0 ) {
                this.logger.info("更新顾客关注状态成功");
            }
        }

        WxMpXmlOutMessage responseResult = null;
        try {
            responseResult = this.handleSpecial(wxMpXmlMessage);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }
        if(responseResult != null) {
            return responseResult;
        }

        try {
            return new TextBuilder().build("感谢关注", wxMpXmlMessage,wxMpService);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 处理特殊请求，比如如果是扫码进来的，可以做相应的处理
     */
    private WxMpXmlOutMessage handleSpecial(WxMpXmlMessage wxMessage) throws Exception {
        return null;
    }
}